package com.heima.account.action;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.account.entity.Account;
import com.heima.account.entity.AccountFreeze;
import com.heima.account.service.IAccountFreezeService;
import com.heima.account.service.IAccountService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountActionImpl implements AccountAction {
    @Autowired
    private IAccountFreezeService freezeService;
    @Autowired
    private IAccountService iAccountService;
    @Override
    public void deduct(Integer userId, Integer money) {
        //预留资源
        //扣减账户可用余额
        LambdaUpdateWrapper<Account> update = new LambdaUpdateWrapper<>();
        update.eq(Account::getUserId, userId);
        update.setSql("money=money-" + money);
        iAccountService.update(update);
        //添加冻结余额
        AccountFreeze freeze = new AccountFreeze();
        //获取全局事务id
        freeze.setXid(RootContext.getXID());
        freeze.setUserId(userId);
        freeze.setFreezeMoney(money);
        freezeService.save(freeze);
    }

    @Override
    public boolean confirm(BusinessActionContext context) {
        //删除冻结余额
        //根据主键删除记录
        String xid = context.getXid();
       freezeService.removeById(xid);
        return true;
    }

    @Override
    public boolean cancel(BusinessActionContext context) {
//查询冻结余额
        String xid = context.getXid();
        AccountFreeze accountFreeze=freezeService.getById(xid);
        if (accountFreeze!=null) {
            //将冻结金额加到可用余额中
            LambdaUpdateWrapper<Account> update = new LambdaUpdateWrapper<>();
            update.eq(Account::getUserId, accountFreeze.getUserId());
            update.setSql("money=money+" + accountFreeze.getFreezeMoney());
            iAccountService.update(update);
            //删除冻结余额
            freezeService.removeById(xid);
        }

        return true;
    }
}
